package com.dc.aimc.auth.security;

import com.dc.aimc.auth.service.*;
import com.dc.aimc.user.entity.User;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 自定义获取用户信息详情服务
 */
@Log4j2
@Service
public class AimcUserDetailsService implements UserDetailsService {

    @Autowired
    private AuthService authService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户基本信息
        User userInfo = authService.getUserInfo(username);
        if (userInfo == null || userInfo.getId() == null) {
            throw new UsernameNotFoundException("查询不到该用户");
        }
        // 查询用户角色权限信息
        List<SimpleGrantedAuthority> authorities = authService.getAuthorities(userInfo.getId());
        // 封装为用户详细信息
        org.springframework.security.core.userdetails.User userDetails  = new org.springframework.security.core.userdetails.User(username, userInfo.getPassword(), authorities);
        log.info("获取用户详细信息: {}", userDetails);
        return userDetails;
    }
}
